import axios from "axios";
const TpHeaders = [
  {
    "Content-type": "application/x-www-form-urlencoded;charset=UTF-8",
  },
  {
    "Content-type": "multipart/form-data",
  },
];
axios.defaults.baseURL = "";
axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
axios.defaults.headers.get["Content-Type"] = "application/json;charset=UTF-8";
axios.defaults.timeout = 30000;
// request拦截器
axios.interceptors.request.use(
  (config) => {
    return config;
  },
  (err) => {
    console.log("错误: ", err);
    Promise.reject(err);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (res) => {
    if (res.status == 200) {
      return Promise.resolve(res);
    } else {
      return Promise.reject(res);
    }
  },
  (err) => {
    return Promise.reject(err);
  }
);
export default {
  get(url: string, params: any, json = true) {
    return new Promise((resolve, rejects) => {
      if (json) {
        axios({
          url,
          method: "GET",
          data: JSON.stringify(params),
        })
          .then((res) => {
            resolve(res.data);
          })
          .catch((err) => {
            rejects(err);
          });
      } else {
        axios({
          headers: TpHeaders[0],
          url,
          method: "GET",
          data: params,
        })
          .then((res) => {
            resolve(res.data);
          })
          .catch((err) => {
            rejects(err);
          });
      }
    });
  },

  post(url: string, data: any, json = true) {
    return new Promise((resolve, rejects) => {
      if (json) {
        axios({
          url,
          method: "POST",
          data: JSON.stringify(data),
        })
          .then((res) => {
            resolve(res.data);
          })
          .catch((err) => {
            rejects(err);
          });
      } else {
        axios({
          headers: TpHeaders[0],
          url,
          method: "POST",
          data: data,
        })
          .then((res) => {
            resolve(res.data);
          })
          .catch((err) => {
            rejects(err);
          });
      }
    });
  },
  upload(url: string, blob: Blob) {
    return new Promise((resolve, rejects) => {
      axios({
        url,
        headers: TpHeaders[1],
        method: "POST",
        data: blob,
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          rejects(err);
        });
    });
  },
};
